package com.wshare.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import com.wshare.entity.Permission;
import com.wshare.entity.Role;
import com.wshare.service.interfaces.IRoleService;


public class AccountPermissionEvaluator implements PermissionEvaluator {

	
	@Autowired
	IRoleService roleService;
	
	@Override
	public boolean hasPermission(Authentication authen, Object type, Object permission) {
		System.out.println("has permission");
		String perm= String.valueOf(permission);
		String[] listPerm = perm.split(",");
		return getRole(authen, listPerm);
		
	}
	
	@Override
	public boolean hasPermission(Authentication arg0, Serializable arg1,
			String arg2, Object arg3) {
		System.out.println("has permission arg");
		
		return false;
	}
	
	private boolean getRole(Authentication authentication,String[] perm) {
		System.out.println("get role");
		List<GrantedAuthority> listGA=(List<GrantedAuthority>) authentication.getAuthorities();
		List<Role> listRole= new ArrayList<Role>();
		for (GrantedAuthority ga : listGA) {
			System.out.println(ga.getAuthority());
			Role role=roleService.getByCol("rolName",ga.getAuthority()).get(0); 
			listRole.add(role);
		}
		boolean flag=false;
	
		System.out.println(listRole.size());
		for (Role role: listRole)
		{
			
			for (Permission rolePer :role.getlPermissions()) {
				for (String controllerPer : perm ) {
					if(rolePer.getPerName().equals(controllerPer)) flag=true;
				}
			}
		}
		return flag;
	}
}
